﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Reflection;

namespace InstantSpine.Core
{
    public static class EnumExtensions
    {
        /// <summary>
        /// extracts the description of an enum value from
        /// it's System.ComponentModel.DescriptionAttribute
        /// </summary>
        /// <param name="value">the enum value with an attached description</param>
        /// <returns>description string; null if no description attached</returns>
        public static string GetDescription(this Enum value)
        {
            Type type = value.GetType();
            string name = Enum.GetName(type, value);
            if (name != null)
            {
                FieldInfo field = type.GetField(name);
                if (field != null)
                {
                    DescriptionAttribute attr =
                           Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
                    if (attr != null)
                        return attr.Description;                    
                }                
            }
            return null;
        }
    }
}
